package com.example.demo.task;

import com.example.demo.domain.CombineClause;
import com.example.demo.domain.SingleClause;
import com.example.demo.domain.exam.Exam;
import com.example.demo.service.exam.ExamService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class PeopleCountTask {

    private final static int FIVE_MINUTES = 5 * 60 * 1000;

    public final static String STRING_PEOPLE_COUNT = "__people";

    private final ExamService examService;

    private final RedisTemplate<Object, Object> redisTemplate;

    @Scheduled(initialDelay = FIVE_MINUTES, fixedDelay = 60 * 1000)
    public void run() {
        log.info("计算考试人数开始");
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        List<Exam> exams = examService.getExamByClause(CombineClause.and(
                SingleClause.greaterThanEqual("start_time", currentTime),
                SingleClause.lessThan("end_time", new Timestamp(currentTime.getTime() - FIVE_MINUTES))
        ));
        if (CollectionUtils.isEmpty(exams)) {
            return;
        }
        Map<Long, Exam> map = exams.stream().collect(Collectors.toMap(Exam::getId, e -> e));
        map.forEach((id, exam) -> {
            Long companyId = exam.getCompanyId();
            int num = (int) Optional.ofNullable(redisTemplate.opsForHash().get(STRING_PEOPLE_COUNT, companyId + "__" + id)).orElse(0);
            exam.setAttendNum(num);
        });
        examService.updateExams(exams);
        log.info("计算考试人数结束");
    }

}
